"""ChameleonBot by AllanDemaon - 2009 Copyleft: All wrongs reserverd
File: Main.py"""

import httplib
from urllib import urlencode
from urllib2 import *
import cookielib
import BrowserDefs
from BrowserDefs import *
import re

DEBUG = 1
httplib.HTTPConnection.debuglevel=1


ChameleonURL="http://www.acervobiblioteca.ufu.br:8000/cgi-bin/gw_46_4_2/chameleon"
sessionid = None

ch = cookielib.CookieJar()

def savepage(page, n=0, path=r"G:\UFU Biblio\testepage"):
	path = path + str(n) + ".html"
	open(path,'w').write(page)

def build_opener_WD():
	abstracthttphandler=AbstractHTTPHandler(debuglevel=DEBUG)
	http_handler = HTTPHandler(debuglevel=DEBUG)
	https_handler = HTTPSHandler(debuglevel=DEBUG)
	httpredirecthandler = HTTPRedirectHandler()
	cookie_handler = HTTPCookieProcessor(ch)
	handlers = [abstracthttphandler,http_handler, https_handler, cookie_handler,httpredirecthandler]
	opener = build_opener(*handlers)
	opener.cookie_jar = ch
	return opener

def request(url, data = None):
	r = Request(url,data)
	for i,e in BrowserDefs.MozillaHeaders.items():
		r.add_header(i,e)
	return r

def fetch(url):
	return urlopen(request(url)).read()


def getin(login, password):
	install_opener(build_opener_WD())
	pa = fetch(ChameleonURL)
	global sessionid
	sessionid=re.search('<input type="hidden" name="sessionid" value="(\\d*)">',pa,2).groups()[0]
	loginpostdata=BrowserDefs.ChameleonLoginData
	loginpostdata["patronid"]=login
	loginpostdata["patronpassword"]=password
	loginpostdata["sessionid"]=sessionid
	data = urlencode(loginpostdata)
	req = request(ChameleonURL,data)
	req.add_header('Referer',ChameleonURL)
	pa = urlopen(req).read()
#	if not re.search("Ocorreu erro de login",pa,2):
#		raise "Login errado (User or Pass wrong)"
	return pa


def renew(login):
	global sessionid
	AtividadesAddress = ChameleonURL
	AtividadesAddress+=r'?patronhost=babao.dr.ufu.br%201111%20DEFAULT&search=PATRON&function=PATRONACTIVITY&SourceScreen=PATRONATTEMPT&skin=default&conf=.%2fchameleon.conf&lng=pt&u1=12&itemu1=12&pos=1&prevpos=1&sessionid='
	AtividadesAddress+= sessionid + '&'
	p=fetch(AtividadesAddress)
	formRenewData=formRenewDefaultData
	formRenewData["sessionid"]=sessionid
	formRenewData["patronid"]=login
	booklist = re.findall(BookEntryPatternS1,p,2)
	booklist.extend(re.findall(BookEntryPatternS2,p,2))
	data = urlencode(formRenewData)
	renovados=0
	for l in booklist:
		data+='&itembarcode='+l#[-1]
		renovados+=1
		#print "Renovando: ",l[1][:30],'  (',l[-3],')'
		print "Renovando: ",'  (',l,')'
	if renovados==0:
		raise TypeError("Nenhuma entrada de livro encontrada")
	else:
		print "Talvez ",renovados," com suscesso."
	data+="&submit=Renovar"
	req = request(ChameleonURL,data)
	pa = urlopen(req).read()
	return pa


def do(login , password):
	p1=getin()
	print "Logado\nRenovando..."
	p2=renew(login)
	savepage(p2)
	print "Renovado com sucesso!(?)"
	
	

